/**
 Copyright (c) 2007, Fanhuagang

 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, 
 are permitted provided that the following conditions are met:

 Redistributions of source code must retain the above copyright notice, this list 
 of conditions and the following disclaimer. 
 Redistributions in binary form must reproduce the above copyright notice, this 
 list of conditions and the following disclaimer in the documentation and/or other 
 materials provided with the distribution. 
 Neither the name of the Fanhuagang nor the names of its contributors may be used 
 to endorse or promote products derived from this software without specific prior 
 written permission. 

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 */
package van.mvn;

import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import org.apache.maven.model.Dependency;
import van.index.Indexer;

import java.util.Set;

/**
 * An action handler to handle the editor's popup menu action.
 * When user click "Add dependency" menu, it will popup a Search maven repository dialog.
 * when user make choice, it will add a dependency section to pom.xml.
 * <p/>
 * User: Fanhuagang
 * Date: 2007-11-18
 * Time: 10:32:25
 */
public class AddDependencyActionHandler extends EditorWriteActionHandler {
    public void executeWriteAction(Editor editor, DataContext dataContext) {

        final Project project = editor.getProject();

        XmlFile xmlFile = (XmlFile) DataKeys.PSI_FILE.getData(dataContext);

        if (xmlFile == null) return;

        MavenRepositorySearchDialog dialog = new MavenRepositorySearchDialog(project, false, "");
        dialog.setTitle("Search Dependency library");
        dialog.show();
        if (!dialog.isOK()) return;

        Object result = dialog.getData();
        try {
            if (result instanceof Indexer.FileInfo) {
                Dependency dependency = ((Indexer.FileInfo) result).getDependency();
                addDependency(xmlFile, dependency);
            } else if (result instanceof Indexer.ArtifactInfo) {
                // If we have an ArtifactInfo, we add the first FileInfo it contains
                // which corresponds to the latest version of the artifact.
                Set files = ((Indexer.ArtifactInfo) result).files;
                if ((files != null) && (files.size() > 0)) {
                    Object file = files.iterator().next();
                    if (file instanceof Indexer.FileInfo) {
                        Dependency dependency = ((Indexer.FileInfo) file).getDependency();
                        addDependency(xmlFile, dependency);
                    }
                }
            }

        } catch (IncorrectOperationException e1) {
            e1.printStackTrace();
        }


    }

    private void addDependency(XmlFile pomXml, Dependency dependency) throws IncorrectOperationException {
        final XmlTag rootTag = pomXml.getDocument().getRootTag();
        if (rootTag != null && "project".equals(rootTag.getName())) {
            XmlTag dependencies = rootTag.findFirstSubTag("dependencies");
            if (dependencies == null) {
                dependencies = (XmlTag) rootTag.add(rootTag.createChildTag("dependencies", rootTag.getNamespace(), null, false));
            }

            XmlTag dependencyTag = (XmlTag) dependencies.add(dependencies.createChildTag("dependency", dependencies.getNamespace(), null, false));
            dependencyTag.add(dependencyTag.createChildTag("groupId", dependencyTag.getNamespace(), dependency.getGroupId(), false));
            dependencyTag.add(dependencyTag.createChildTag("artifactId", dependencyTag.getNamespace(), dependency.getArtifactId(), false));
            dependencyTag.add(dependencyTag.createChildTag("version", dependencyTag.getNamespace(), dependency.getVersion(), false));

            rootTag.getManager().getCodeStyleManager().reformat(dependencies);
        }

    }

    public boolean isEnabled(Editor editor, DataContext dataContext) {
        VirtualFile file = DataKeys.VIRTUAL_FILE.getData(dataContext);
        if (file == null) return false;
        return "pom.xml".equals(file.getName());
    }
}
